package com.g2.rpc.spring;

import cn.hutool.json.JSONUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import com.g2.rpc.config.ProtocolConfig;
import com.g2.rpc.config.RegistryConfig;

import java.lang.reflect.Field;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author lingjiu.kong
 * @version 1.0
 * @date 2021-03-03 23:24
 */
public class ConfigRegistrar implements EnvironmentAware, ImportBeanDefinitionRegistrar {

    private static Logger log = Logger.getLogger("g2rpc");

    private Environment environment;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Class<?> configClass = RegistryConfig.class;
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(configClass);
        Field[] fields = configClass.getDeclaredFields();
        for (Field field : fields) {
            builder.addPropertyValue(field.getName(), environment.getProperty("register.url." + field.getName()));
        }

        registry.registerBeanDefinition("registryConfig", builder.getBeanDefinition());

        log.info("注册中心配置：" + JSONUtil.toJsonStr(builder.getBeanDefinition()));

        configClass = ProtocolConfig.class;
        builder = BeanDefinitionBuilder.genericBeanDefinition(configClass);
        fields = configClass.getDeclaredFields();
        for (Field field : fields) {
            builder.addPropertyValue(field.getName(), environment.getProperty("g2rpc.protocol." + field.getName()));
        }

        registry.registerBeanDefinition("protocolConfig", builder.getBeanDefinition());
        log.info("协议配置：" + JSONUtil.toJsonStr(builder.getBeanDefinition()));
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}